package com.pay.ioopos.activity;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.pay.ioopos.KeyInfo;
import com.pay.ioopos.R;
import com.pay.ioopos.fragment.NetworkFragment;
import com.pay.ioopos.fragment.TipVerticalFragment;

import static com.pay.ioopos.KeyInfo.KEY_CANCEL;
import static com.pay.ioopos.KeyInfo.KEY_ENTER;
import static com.pay.ioopos.KeyInfo.KEY_NUM_1;
import static com.pay.ioopos.KeyInfo.KEY_NUM_2;
import static com.pay.ioopos.KeyInfo.KEY_NUM_3;
import static com.pay.ioopos.KeyInfo.KEY_NUM_4;
import static com.pay.ioopos.fragment.TipFragment.TipType.SUCCESS;

public class NetworkActivity extends AbstractActivity {
    private static final String TAG = NetworkActivity.class.getSimpleName();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_network);
        setMainFragment(new NetworkFragment());
    }

    @TargetApi(Build.VERSION_CODES.O)
    @Override
    public boolean onKeyDown(KeyInfo keyInfo) {
        if (mainFragment instanceof NetworkFragment) {
            if (keyInfo == KEY_NUM_1) {
                openWifi(true);
                open4G(true);
                setMainFragment(new TipVerticalFragment(SUCCESS, "已切换至自动上网"));
            } else if (keyInfo == KEY_NUM_2) {
                openWifi(false);
                open4G(false);
                setMainFragment(new TipVerticalFragment(SUCCESS, "已切换至网线上网"));
            } else if (keyInfo == KEY_NUM_3) {
                openWifi(true);
                open4G(false);
                setMainFragment(new TipVerticalFragment(SUCCESS, "已切换至WIFI上网"));
            } else if (keyInfo == KEY_NUM_4) {
                openWifi(false);
                open4G(true);
                setMainFragment(new TipVerticalFragment(SUCCESS, "已切换至4G上网"));
            }
        }
        if (keyInfo == KEY_ENTER || keyInfo == KEY_CANCEL ) {
            Intent intent = new Intent(this, ConnectActivity.class);
            startActivity(intent);
        }
        return false;
    }

    private void openWifi(boolean bool) {
        WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
        wifiManager.setWifiEnabled(bool);
    }

    @TargetApi(Build.VERSION_CODES.O)
    private void open4G(boolean bool) {
        TelephonyManager telManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        try {
            telManager.setDataEnabled(bool);
        } catch (Exception e) {
            Log.e(TAG, "open4G: ", e);
            //showToast("4G开关异常：" + e.getMessage());
        }
    }
}
